<template>
<div class="add-datasource-table-wrapper">
    <Spin size="large" fix v-if="loading"></Spin> <!-- 加载动画 -->
    <Tabs v-model="currentTab">
        <TabPane label="单表数据源" name="table">
            <Row>
                <Col :span="6">
                    <div class="left-border">
                        <div style="border-bottom: 1px solid #e9e9e9; padding-bottom:6px; margin-bottom:6px; margin-right: 8px; float: left; width:100%">
                            <p v-if="!loading" class="" style="font-size: 13px; color: #979797;">
                                <span class="pull-left m-r-15"><i :class="'zlstbd-icon-' + dsConnect.connectType" :title="dsConnect.connectType"></i>
                                {{ dsConnect.connectHost }}:{{ dsConnect.connectPort }}
                                </span>
                                <span class="pull-left">{{dsConnect.databaseName}}</span>
                            </p>
                        </div>
                        <p class="m-b-10">
                            <Checkbox
                                :indeterminate="indeterminate"
                                :value="checkAll"
                                @click.prevent.native="handleCheckAll">全选</Checkbox>
                            <span class="pull-right m-r-10" style="font-size: 13px; color: #979797;">
                                共 <span style="color: #6cc8d7">{{tableList.length}}</span> /
                                <span>已选 <span style="color: #6cc8d7">{{submitObj.tableList.length}}</span></span>
                            </span>
                        </p>
                        <CheckboxGroup v-model="selectedTableList" @on-change="selectedTableListChange" class="check-box-group fix-scrollbar">
                            <Checkbox v-for="(table, tIndex) in tableList" :key="tIndex" :label="table" class="check-box-label" :title="table">
                            </Checkbox>
                        </CheckboxGroup>
                    </div>
                </Col>
                <Col :span="18" style="padding-left: 16px;">
                    <Row style="border-bottom: 1px solid #e9e9e9; padding-bottom: 8px; margin-bottom: 12px;">
                        <Col :span="10" :offset="1">已选表</Col>
                        <Col :span="11">数据源名称</Col>
                    </Row>
                    <Form :model="submitObj" ref="tableForm" class="table-form fix-scrollbar">
                        <Row v-for="(item, iIndex) in submitObj.tableList" :key="iIndex">
                            <Col :span="9" :offset="1" style="margin-top: 5px;">
                                <span>{{ item.tableName }}</span>
                            </Col>
                            <Col :span="11" :offset="1">
                                <FormItem
                                    :prop="'tableList.' + iIndex     + '.datasourceName'"
                                    :rules="{required: true, message: '请输入数据源名称！'}">
                                    <Input clearable v-model="item.datasourceName" />
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <p style="font-size: 13px; color: #979797; padding-top: 12px; border-top: 1px solid #e9e9e9;">
                <Icon type="ios-alert-outline" /> 点击保存后将批量生成选中表数量的数据源，即一张数据库表生成一个数据源。
            </p>
        </TabPane>
        <TabPane label="自定义SQL" name="sql">
            <Form :model="datasource" :label-width="100" class="p-r-20 m-t-15">
                <FormItem label="数据源名称" prop="datasourceName"
                :rules="{required: true, message:'请输入数据源名称！'}">
                    <Input v-model="datasource.datasourceName" clearable></Input>
                </FormItem>
                <FormItem label="SQL语句" prop="customizeSql"
                :rules="{required: true, message:'请输入SQL语句！'}">
                    <Input v-model="datasource.customizeSql" type="textarea" :rows="3"></Input>
                </FormItem>
            </Form>
            <Row>
                <Col :span="3" :offset="21" class="p-r-20">
                    <Button class="pull-right" @click="executeSQL"><i class="zlstbd-icon-continue m-r-5"></i>执行</Button>
                </Col>
            </Row>
        </TabPane>
    </Tabs>
    <fullModal v-model="modal.datasource">
        <div>
            <div class="m-b-10" style="text-align: center;font-size: 16px;">
                <b>样例数据展示</b>
            </div>
            <Table :columns="heads" :data="sqlDataSourceList"></Table>
        </div>
    </fullModal>
</div>
</template>

<script>
import util from 'util'
import getData from 'getData'
import fullModal from '@/components/common/fullmodal.vue'
export default {
    name: 'AddDatasourceTable',

    components:{fullModal},
    props: {
        datasource: {
            type: Object,
            required: true
        }
    },

    computed: {
        submitObj() {
            var res = util.util.cloneObj(this.datasource);
            delete res.sql;
            var tableList = [];
            for (var i = 0; i < this.selectedTableList.length; i++) {
                var item = this.selectedTableList[i];
                var datasourceName = this.dsConnect.databaseName + '_' + item;
                var submitTable = {
                    datasourceName: datasourceName,
                    tableName: item
                }
                tableList.push(submitTable);
            }
            res.tableList = tableList;
            return res;
        }
    },

    data () {
        return {
            indeterminate: false,
            checkAll: false,
            selectedTableList: [],
            tableList: [],
            dsConnect: {},
            loading: false,
            currentTab: 'table',
            modal: {
                datasource:false,
            },
            heads:[],
            sqlDataSourceList:[],
        }
    },

    watch: {
        // datasource: {
        //     deep: true,
        //     handler(val) {
                // this.queryDsConnectTables();
                // this.queryDsConnectDetail();
            // }
        // }
    },

    methods: {
        next() {
            var reqPath, reqData;
            if (this.currentTab == 'table') {
                reqPath = 'batchAddDatasource';
                reqData = this.submitObj;
                reqData.executeType='table';
            } else if (this.currentTab == 'sql') {
                reqPath = 'saveDatasource';
                reqData = this.datasource;
                reqData.executeType='sql';
            }
            getData.post(reqPath, reqData).then(res => {
                if (res.status == 200 && res.data.code == '000') {
                    this.$Message.success('新增数据源成功！');
                    this.$emit('next')
                } else {
                    this.$Message.error('新增数据源失败，请检查网络或联系管理员！');
                    console.error(res);
                }
            });
        },
        queryDsConnectTables() {
            this.loading = true;
            getData.get('getDsConnectTables', {}, this.datasource.connectId).then(res => {
                this.loading = false;
                if (res.status == 200 && res.data.code == '000') {
                    this.tableList = res.data.data;
                } else {
                    this.$Message.error('查询数据库表失败，请检查网络或联系管理员！');
                    console.error(res);
                }
            });
        },
        queryDsConnectDetail() {
            this.loading = true;
            getData.get('getDsConnectDetail', {}, this.datasource.connectId).then(res => {
                this.loading = false;
                if (res.status == 200 && res.data.code == '000') {
                    this.dsConnect = res.data.data;
                } else {
                    this.$Message.error('查询数据库连接失败，请检查网络或联系管理员！');
                    console.error(res);
                }
            });
        },
        handleCheckAll () {
            if (this.indeterminate) {
                this.checkAll = false;
            } else {
                this.checkAll = !this.checkAll;
            }
            this.indeterminate = false;

            if (this.checkAll) {
                this.selectedTableList = this.tableList;
            } else {
                this.selectedTableList = [];
            }
        },
        selectedTableListChange (data) {
            this.selectedTableList = data;
            if (data.length === this.tableList.length) {
                this.indeterminate = false;
                this.checkAll = true;
            } else if (data.length > 0) {
                this.indeterminate = true;
                this.checkAll = false;
            } else {
                this.indeterminate = false;
                this.checkAll = false;
            }
        },
        executeSQL(){ //
            getData.post("sqlExecuteDatasource", this.datasource).then(res => {
                if (res.status == 200 && res.data.code == '000') {
                    if(res.data.data.code == '1060'){
                        this.$Message.error(res.data.data.errorMsg);
                    }else{
                        this.heads = res.data.data[0];
                        this.sqlDataSourceList = res.data.data[1];
                        this.modal.datasource = true;
                    }
                } else {
                    this.$Message.error('SQL执行出错,请检查网络或者联系管理员！');
                }
            });
        },
    },

    mounted () {
        this.queryDsConnectTables();
        this.queryDsConnectDetail();
    }
}
</script>

<style lang="less">
.add-datasource-table-wrapper {
    position: relative;
    .ivu-tabs-bar {
        margin-bottom: 8px;
    }
    .left-border {
        min-height: 46vh;
        border-right: 1px solid #979797;
    }
    .check-box-group {
        max-height: calc(~'100vh - 420px');
        overflow: auto;
        .check-box-label {
            padding: 4px 0;
            width: 96%;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .check-box-label:hover {
            background: #f5f7f9;
        }
    }
    .table-form {
        max-height: calc(~'100vh - 400px');
        overflow: auto;
    }
}
</style>
